import { Response } from 'express';
import { AuthenticatedRequest } from '../types/auth';
import { AIHomeworkGenerationService } from '../services/aiHomeworkGenerationService';
import { ApiError } from '../utils/ApiError';
import { StatusCodes } from '../constants/statusCodes';
import { logger } from '../utils/logger';
import { Role, Difficulty, QuestionType } from '@prisma/client';
import { z } from 'zod';

// 验证Schema
const homeworkCriteriaSchema = z.object({
  subject: z.string().min(1, '学科不能为空'),
  gradeLevel: z.number().int().min(1).max(12),
  topics: z.array(z.string()).min(1, '至少需要一个主题'),
  difficulty: z.enum([Difficulty.EASY, Difficulty.MEDIUM, Difficulty.HARD]),
  questionCount: z.object({
    multipleChoice: z.number().int().min(0),
    openEnded: z.number().int().min(0)
  }).refine(data => data.multipleChoice + data.openEnded > 0, {
    message: '至少需要一道题目'
  }),
  estimatedDuration: z.number().int().min(10).max(180),
  excludeQuestionIds: z.array(z.string().uuid()).optional()
});

const knowledgePointsSchema = z.object({
  knowledgePoints: z.array(z.string()).min(1, '至少需要一个知识点'),
  subject: z.string().min(1, '学科不能为空'),
  gradeLevel: z.number().int().min(1).max(12),
  difficulty: z.enum([Difficulty.EASY, Difficulty.MEDIUM, Difficulty.HARD]),
  questionCount: z.object({
    multipleChoice: z.number().int().min(0),
    openEnded: z.number().int().min(0)
  }).refine(data => data.multipleChoice + data.openEnded > 0, {
    message: '至少需要一道题目'
  }),
  estimatedDuration: z.number().int().min(10).max(180)
});

const templateGenerationSchema = z.object({
  templateId: z.string().uuid('无效的模板ID'),
  customizations: z.object({
    difficulty: z.enum([Difficulty.EASY, Difficulty.MEDIUM, Difficulty.HARD]).optional(),
    topics: z.array(z.string()).optional(),
    estimatedDuration: z.number().int().min(10).max(180).optional()
  })
});

export const aiHomeworkGenerationController = {
  // 生成作业
  async generateHomework(req: AuthenticatedRequest, res: Response) {
    try {
      if (!req.user) {
        throw new ApiError(StatusCodes.UNAUTHORIZED, '未授权访问');
      }

      // 验证教师权限
      if (req.user.role !== Role.ADMIN && req.user.role !== Role.TEACHER) {
        throw new ApiError(StatusCodes.FORBIDDEN, '无权生成作业');
      }

      const criteria = homeworkCriteriaSchema.parse(req.body);

      const homework = await AIHomeworkGenerationService.generateHomework(criteria);

      logger.info('作业生成成功', {
        teacherId: req.user.id,
        homeworkId: homework.id
      });

      res.json({
        success: true,
        data: homework
      });
    } catch (error) {
      logger.error('作业生成失败', {
        context: 'aiHomeworkGenerationController.generateHomework',
        error
      });
      throw error;
    }
  },

  // 根据知识点生成作业
  async generateByKnowledgePoints(req: AuthenticatedRequest, res: Response) {
    try {
      if (!req.user) {
        throw new ApiError(StatusCodes.UNAUTHORIZED, '未授权访问');
      }

      // 验证教师权限
      if (req.user.role !== Role.ADMIN && req.user.role !== Role.TEACHER) {
        throw new ApiError(StatusCodes.FORBIDDEN, '无权生成作业');
      }

      const { knowledgePoints, ...criteria } = knowledgePointsSchema.parse(req.body);

      const homework = await AIHomeworkGenerationService.generateByKnowledgePoints(
        knowledgePoints,
        criteria
      );

      logger.info('基于知识点生成作业成功', {
        teacherId: req.user.id,
        homeworkId: homework.id,
        knowledgePoints
      });

      res.json({
        success: true,
        data: homework
      });
    } catch (error) {
      logger.error('基于知识点生成作业失败', {
        context: 'aiHomeworkGenerationController.generateByKnowledgePoints',
        error
      });
      throw error;
    }
  },

  // 获取作业模板列表
  async getHomeworkTemplates(req: AuthenticatedRequest, res: Response) {
    try {
      if (!req.user) {
        throw new ApiError(StatusCodes.UNAUTHORIZED, '未授权访问');
      }

      const { subject, gradeLevel } = req.query;

      if (!subject || !gradeLevel) {
        throw new ApiError(StatusCodes.BAD_REQUEST, '必须提供学科和年级');
      }

      const templates = await AIHomeworkGenerationService.getHomeworkTemplates(
        String(subject),
        Number(gradeLevel)
      );

      res.json({
        success: true,
        data: templates
      });
    } catch (error) {
      logger.error('获取作业模板失败', {
        context: 'aiHomeworkGenerationController.getHomeworkTemplates',
        error
      });
      throw error;
    }
  },

  // 根据模板生成作业
  async generateFromTemplate(req: AuthenticatedRequest, res: Response) {
    try {
      if (!req.user) {
        throw new ApiError(StatusCodes.UNAUTHORIZED, '未授权访问');
      }

      // 验证教师权限
      if (req.user.role !== Role.ADMIN && req.user.role !== Role.TEACHER) {
        throw new ApiError(StatusCodes.FORBIDDEN, '无权生成作业');
      }

      const { templateId, customizations } = templateGenerationSchema.parse(req.body);

      const homework = await AIHomeworkGenerationService.generateFromTemplate(
        templateId,
        customizations
      );

      logger.info('根据模板生成作业成功', {
        teacherId: req.user.id,
        homeworkId: homework.id,
        templateId
      });

      res.json({
        success: true,
        data: homework
      });
    } catch (error) {
      logger.error('根据模板生成作业失败', {
        context: 'aiHomeworkGenerationController.generateFromTemplate',
        error
      });
      throw error;
    }
  }
};
